package cn.com.ghy.android.widget.coopvisit;

import java.io.Serializable;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.ghy.android.bean.CoopVisitBigShopInfoBean;
import cn.com.ghy.android.bean.CoopVisitInfoBean;
import cn.com.ghy.android.bean.CoopVisitSmallShopInfoBean;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.VsPartOpeService;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;

/**
 * @软件著作权:金红叶纸业集团有限公司
 * @系统名称:SFA系统
 * @Description:小店信息列表显示
 * @author wuz  @date 2011-6-22 14:16:05
 * @版本历史:v1.0
 * @Copyright:Copyright (c) 2011-2012 
 */

public class CoopVisitSmallShopList extends Activity {

	private EditText txtCustomerId = null;
	private EditText txtCustomerName = null;
	private TextView labTxtDate = null;
	private ListView listSmallShopInfoList = null;
	private Button btnQuery = null;
	private ProgressDialog progressDialog = null;

	private LoginInfoBean loginInfo = null;
	private static final String VSTYPE = CommonStatic.VSTYPE_SMALL;
	private String vsid = "";
	private String vsname = "";
	private String vsdate = "";
	private Bundle bundle = null;
	private Intent intent = null;

	private CoopVisitInfoListAadpter coopVisitInfoListAadpter = null;

	private HttpThread httpThread = null;

	private DisposeException disposeException = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.coop_visit_small_shop_list);
		getSession();
		findView();
		init();
		addListener();
	}

	private void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		loginInfo = ((ComStaticApp) getApplication()).getLoginInfo();
	}

	private void findView() {
		txtCustomerId = (EditText) findViewById(R.id.txtCustomerId);
		txtCustomerName = (EditText) findViewById(R.id.txtCustomerName);
		labTxtDate = (TextView) findViewById(R.id.labTxtDate);
		btnQuery = (Button) findViewById(R.id.btnQuery);
		listSmallShopInfoList = (ListView) findViewById(R.id.listSmallShopInfoList);
	}

	private void init() {
		labTxtDate.setText(loginInfo.getNowdate().substring(0, 10));
	}

	private void addListener() {
		btnQuery.setOnClickListener(btnListener);
		listSmallShopInfoList.setOnItemClickListener(adapterListener);
	}

	private boolean getData() {
		vsid = txtCustomerId.getText().toString().trim();
		vsname = txtCustomerName.getText().toString().trim();
		vsdate = labTxtDate.getText().toString().trim();
		if ("".equals(vsid) && "".equals(vsname)) {
			Toast.makeText(CoopVisitSmallShopList.this, "请输入选择条件!", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private View.OnClickListener btnListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			Button button = (Button) v;
			switch (button.getId()) {
				case R.id.btnQuery :
					if (!getData()) {
						return;
					}
					CoopVisitBigShopListAsyncTask task = new CoopVisitBigShopListAsyncTask();
					task.doStart(handler);
					break;
			}

		}
	};

	private OnItemClickListener adapterListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			CoopVisitInfoBean bean = (CoopVisitInfoBean) parent.getItemAtPosition(position);
			showDialog(CoopVisitSmallShopList.this, position, bean);
		}

	};

	private class CoopVisitInfoListAadpter extends BaseAdapter {

		private Context context = null;
		private List<CoopVisitInfoBean> list = null;

		public CoopVisitInfoListAadpter(Context context, List<CoopVisitInfoBean> list) {
			this.context = context;
			this.list = list;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public CoopVisitInfoBean getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(inflater);
			LinearLayout linearLayout = null;
			if (list.get(position) instanceof CoopVisitInfoBean) {
				linearLayout = (LinearLayout) LayoutInflater.inflate(
						R.layout.coop_visit_small_shop_list_lay, null);
				CoopVisitInfoBean bean = list.get(position);
				TextView tv = (TextView) linearLayout.findViewById(R.id.labTxtSmallShopName);
				tv.setText((position + 1) + "." + bean.getKunnrname());

				tv = (TextView) linearLayout.findViewById(R.id.labTxtSmallShopId);
				tv.setText(bean.getKunnr());

				tv = (TextView) linearLayout.findViewById(R.id.labTxtGrade);
				tv.setText(bean.getDengji());

				tv = (TextView) linearLayout.findViewById(R.id.labTxtIsCoopVisit);
				tv.setText(bean.getIsvisit());
			}
			return linearLayout;
		}

		/*-- 以下为自定义方法 --*/
		public void modify(CoopVisitInfoBean bean, int position) {
			if (position < 0) {
				return;
			}
			list.remove(position);
			list.add(position, bean);
			notifyDataSetChanged();
		}

	}

	@SuppressWarnings("rawtypes")
	private class CoopVisitBigShopListAsyncTask extends AsyncTask {
		private List<CoopVisitInfoBean> list = null;
		private Handler handle = null;

		@SuppressWarnings("unchecked")
		public void doStart(Handler handle) {
			this.handle = handle;
			progressDialog = new ProgressDialog(CoopVisitSmallShopList.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			CoopVisitBigShopListAsyncTask.this.execute();
		}

		@Override
		protected Object doInBackground(Object... params) {
			Message message = null;
			try {
				VsPartOpeService service = new VsPartOpeService();
				list = service.GetVsDateInfo(VSTYPE, vsid, vsname, loginInfo, vsdate);
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}

			progressDialog.dismiss();
			if (null != list && list.size() > 0) {
				listSmallShopInfoList.post(new Runnable() {
					public void run() {
						coopVisitInfoListAadpter = new CoopVisitInfoListAadpter(
								CoopVisitSmallShopList.this, list);
						listSmallShopInfoList.setAdapter(coopVisitInfoListAadpter);
					}
				});
			} else {
				bundle = new Bundle();
				bundle.putString("errorMsg", "该条件下,暂时没有小店信息!");
				message = handle.obtainMessage();
				message.what = CommonStatic.STATE_NORMAL_NULL;
				message.setData(bundle);
				handle.sendMessage(message);
			}

			return null;
		}
	}

	private class HttpThread extends Thread {
		private Handler handle = null;
		private CoopVisitInfoBean bean = null;
		private int position = -1;
		private String visitFlag = null;

		public HttpThread(Handler hander) {
			handle = hander;
		}

		public void doStart(CoopVisitInfoBean bean, int position, String visitFlag) {
			this.bean = bean;
			this.position = position;
			this.visitFlag = visitFlag;
			progressDialog = new ProgressDialog(CoopVisitSmallShopList.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			this.start();
		}

		public void run() {
			Message message = null;
			try {
				String result = null;
				VsPartOpeService service = new VsPartOpeService();
				result = service
						.SetVisitTime(VSTYPE, bean.getKunnr(), visitFlag, loginInfo, vsdate);
				progressDialog.dismiss();
				if ("OK".equals(result)) {
					if (visitFlag.equals(CommonStatic.STYPE_L)) {
						bean.setIsvisit("Y");
						message = handle.obtainMessage();
						bundle = new Bundle();
						bundle.putString("errorMsg", "true");
						bundle.putSerializable("coopVisitInfo", bean);
						bundle.putInt("position", position);
						message.what = CommonStatic.STATE_NORMAL;
					} else if (visitFlag.equals(CommonStatic.STYPE_E)) {
						List<CoopVisitSmallShopInfoBean> list = service.GetVsPartDataForSmallShop(
								VSTYPE, bean.getKunnr(), loginInfo, vsdate);
						message = handle.obtainMessage();
						bundle = new Bundle();
						bundle.putSerializable("coopVisitInfo", bean);
						bundle.putSerializable("coopVisitSmallShopInfoList", (Serializable) list);
						message.what = CommonStatic.STATE_NORMAL;
					}
				} else {
					message = handle.obtainMessage();
					bundle = new Bundle();
					bundle.putString("errorMsg", "false");
					bundle.putString("visitFlag", visitFlag);
					message.what = CommonStatic.STATE_NORMAL;
				}
				message.setData(bundle);
				handle.sendMessage(message);
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}
		}
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(Message m) {
			String errorMsg = m.getData().getString("errorMsg");
			String visitFlag = m.getData().getString("visitFlag");
			final int position = m.getData().getInt("position");
			final CoopVisitInfoBean bean = (CoopVisitInfoBean) m.getData().getSerializable(
					"coopVisitInfo");
			String msg = "";
			List<CoopVisitBigShopInfoBean> list = (List<CoopVisitBigShopInfoBean>) m.getData()
					.getSerializable("coopVisitSmallShopInfoList");
			switch (m.what) {
				case CommonStatic.STATE_NORMAL :
					if ("false".equals(errorMsg)) {
						if (visitFlag.equals(CommonStatic.STYPE_E)) {
							msg = "进店时间更新失败, 请联系管理员!";
						} else if (visitFlag.equals(CommonStatic.STYPE_L)) {
							msg = "离店时间更新失败, 请先进店才能离店!";
						} else {
							msg = "程序异常, 请联系管理员!";
						}
						new AlertDialog.Builder(CoopVisitSmallShopList.this).setTitle("提示信息")
								.setMessage(msg).setPositiveButton("关闭", null).show();
						return;
					} else if ("true".equals(errorMsg)) {
						new AlertDialog.Builder(CoopVisitSmallShopList.this).setTitle("提示信息")
								.setMessage("离店成功!")
								.setPositiveButton("关闭", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dlg, int sumthin) {
										coopVisitInfoListAadpter.modify(bean, position);
									}
								}).show();
						return;
					}
					bundle = new Bundle();
					bundle.putSerializable("coopVisitInfo", bean);
					bundle.putSerializable("coopVisitSmallShopInfoList", (Serializable) list);
					intent = new Intent(CoopVisitSmallShopList.this, CoopVisitSmallShop.class);
					intent.putExtras(bundle);
					CoopVisitSmallShopList.this.startActivity(intent);
					break;
				case CommonStatic.STATE_NORMAL_NULL :
					new AlertDialog.Builder(CoopVisitSmallShopList.this).setTitle("提示信息")
							.setMessage(errorMsg).setNeutralButton("关闭", null).show();
					break;
			}
		}
	};

	private void showDialog(final Context context, final int position, final CoopVisitInfoBean bean) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("提示信息:");
		builder.setMessage("小店名称: " + bean.getKunnrname());
		builder.setPositiveButton("进店", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				httpThread = new HttpThread(handler);
				httpThread.doStart(bean, position, CommonStatic.STYPE_E);
			}
		});
		builder.setNeutralButton("离店", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				httpThread = new HttpThread(handler);
				httpThread.doStart(bean, position, CommonStatic.STYPE_L);
			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}
}
